<template>
  <a-modal
    v-drag-modal="drag"
    :visible="show"
    :destroyOnClose="true"
    :centered="true"
    :maskClosable="false"
    :keyboard="false"
    v-bind="$attrs"
    v-on="$listeners"
    :afterClose="afterClose"
    class="rj-modal"
  >
    <template v-for="slot in slotArr" :slot="slot">
      <slot :name="slot"></slot>
    </template>
  </a-modal>
</template>

<script>
import Vue from 'vue';
import { Modal } from 'ant-design-vue';
// let hasRemove = false;
//设置父页面层级
const setParentsClass = function () {
  Vue.nextTick(() => {
    let hasShowModal = false,
      hasShowDrawer = false;
    const modalArr = document.querySelectorAll('.rj-modal .ant-modal-wrap');

    modalArr.forEach(function (item) {
      //判断是否没有显示的弹窗
      var style = window.getComputedStyle(item);
      if (style.display !== 'none') {
        hasShowModal = true;
      }
    });
    if (!hasShowModal) {
      //有可能弹窗中触发显示弹窗，造成多个弹窗，需要判断只有一个弹窗是才设置
      if (self != top) {
        top.$('body').removeClass('subWebModal');
      }
    } else {
      if (self != top) {
        top.$('body').addClass('subWebModal');
      }
    }
    const drawerArr = document.querySelectorAll('.rj-drawer');
    drawerArr.forEach(function (item) {
      //判断是否没有显示的抽屉弹窗
      const style = window.getComputedStyle(item);
      if (style.display !== 'none' && style.width != '0px') {
        hasShowDrawer = true;
      }
    });
    if (!hasShowDrawer) {
      //有可能弹窗中触发显示弹窗，造成多个弹窗，需要判断只有一个弹窗是才设置
      if (self != top) {
        top.$('body').removeClass('subWebDrawer');
      }
    } else {
      if (self != top) {
        top.$('body').addClass('subWebDrawer');
      }
    }
  });
};
const RjModal = {
  name: 'rj-modal',
  inheritAttrs: false,
  props: {
    visible: {
      typeof: Boolean,
    },
    cancel: {
      typeof: Function,
    },
    drag: {
      typeof: Boolean,
      default: false,
    },
  },
  data() {
    return {
      show: this.visible,
      slotArr: [],
    };
  },
  mounted() {
    this.slotArr = Object.keys(this.$slots);
  },
  beforeUpdate() {},
  destroyed() {
    if (self == top) return; //页面没有被内嵌
    setParentsClass();
  },

  directives: {
    'drag-modal': {
      inserted: function (el, bindings, vnode) {
        let { visible, destroyOnClose } = vnode.componentInstance;
        let { value } = bindings;
        el.$value = value;
        if (!value) return;
        if (!visible) return;
        // 防止未定义 destroyOnClose 关闭弹窗时dom未被销毁，指令被重复调用
        const modal = el.getElementsByClassName('ant-modal')[0];
        const header = el.getElementsByClassName('ant-modal-header')[0];
        //防止弹窗移出浏览器数据 开始
        // const bodyWidth = document.body.offsetWidth;
        // const bodyHeight = document.body.offsetHeight;
        // const modalWidth = modal.offsetWidth || 0;
        // const modalHeigth = modal.offsetHeight || 0;
        // const disx = (bodyWidth - modalWidth) / 2;
        // const disy = (bodyHeight - modalHeigth) / 2;
        //防止弹窗移出浏览器数据 开始
        let left = 0;
        let top = 0;

        // 未定义 destroyOnClose 时，dom未被销毁，关闭弹窗再次打开，弹窗会停留在上一次拖动的位置
        if (!destroyOnClose) {
          left = modal.left || 0;
          top = modal.top || 0;
        }
        header.style.cursor = 'move';
        header.onmousedown = (e) => {
          let startX = e.clientX;
          let startY = e.clientY;
          header.left = header.offsetLeft;
          header.top = header.offsetTop;
          el.onmousemove = (event) => {
            let endX = event.clientX;
            let endY = event.clientY;
            modal.left = header.left + (endX - startX) + left;
            modal.top = header.top + (endY - startY) + top;
            //防止弹窗移出浏览器 开始
            // if (modal.left > disx) {
            //   modal.left = disx;
            // } else if (modal.left < -disx) {
            //   modal.left = -disx;
            // }

            // if (modal.top > disy) {
            //   modal.top = disy;
            // } else if (modal.top < -disy) {
            //   modal.top = -disy;
            // }
            //防止弹窗移出浏览器 结束

            modal.style.left = modal.left + 'px';
            modal.style.top = modal.top + 'px';
          };
          el.onmouseup = () => {
            left = modal.left;
            top = modal.top;
            el.onmousemove = null;
            el.onmouseup = null;
            header.releaseCapture && header.releaseCapture();
          };
          header.setCapture && header.setCapture();
        };
      },

      // 当传进来的值更新的时候触发
      componentUpdated(el, { value }) {
        el.$value = value;
      },
    },
  },
  methods: {
    setParentPage(val) {
      if (self != top) {
        //页面被内嵌
        if (val) {
          top.$('body').addClass('subWebModal');
        } else {
          setParentsClass();
        }
      }
    },
    afterClose() {
      this.$attrs.afterClose && this.$attrs.afterClose();
      setParentsClass();
    },
  },
  watch: {
    visible: {
      handler: function (val) {
        this.show = val;
        this.setParentPage(val);
      },
      immediate: true,
    },
  },
};

RjModal.info = (props) => {
  if (self != top) {
    top.$('body').addClass('subWebModal');
  }
  const customObj = rewriteClose(props);
  return Modal.info({
    ...props,
    ...customObj,
  });
};

RjModal.success = (props) => {
  if (self != top) {
    top.$('body').addClass('subWebModal');
  }
  const customObj = rewriteClose(props);
  return Modal.success({
    ...props,
    ...customObj,
  });
};

RjModal.error = (props) => {
  if (self != top) {
    top.$('body').addClass('subWebModal');
  }
  const customObj = rewriteClose(props);
  return Modal.error({
    ...props,
    ...customObj,
  });
};

RjModal.warning = (props) => {
  if (self != top) {
    top.$('body').addClass('subWebModal');
  }
  const customObj = rewriteClose(props);
  return Modal.warning({
    ...props,
    ...customObj,
  });
};

RjModal.confirm = (props) => {
  if (self != top) {
    top.$('body').addClass('subWebModal');
  }
  const customObj = rewriteClose(props);
  return Modal.confirm({
    ...props,
    ...customObj,
  });
};

const rewriteClose = (props) => {
  return {
    onCancel: () => {
      props.onCancel && props.onCancel();
      if (self != top) {
        setParentsClass();
      }
    },
    onOk: () => {
      props.onOk && props.onOk();
      if (self != top) {
        setParentsClass();
      }
    },
  };
};

RjModal.destroy = Modal.destroy;
RjModal.destroyAll = Modal.destroyAll;

export default RjModal;
</script>

<style></style>
